<template>
  <div id="qiIndexMajor">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" :loading="showLoading" @click="findqiIndexMajorList()"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-square-plus" class="button-blue" content="新增" @click="addModuleDialog()"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-save" class="button-blue" content="保存" @click="saveList"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
      </template>
    </vxe-toolbar>
    <div class="qiIndexMajorTable">
      <vxe-table ref="qiIndexMajorTableRef" :loading="showLoading" class="mytable-scrollbar" align="left" border height="auto" :keep-source="true" :data="qiIndexMajorList" @cell-click="qiIndexMajorRowClick" :row-config="{ isCurrent: true, isHover: true }" :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" resizable show-overflow>
        <vxe-column type="checkbox" align="center" width="26"></vxe-column>
        <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
        <vxe-column field="majorCode" title="专业编码" min-width="100" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.majorCode" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="majorName" title="专业名称" width="300" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.majorName" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="majorGroup" title="专业分组" width="300" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.majorGroup" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="statType" title="统计类型" width="200" :edit-render="{}">
          <template #default="{ row }">
            <span>{{ formatCommon(statTypeList, row.statType) }}</span>
          </template>
          <template #edit="{ row, rowIndex, column }">
            <!-- 选择字典  -->
            <vxe-select v-model="row.statType">
              <vxe-option v-for="hobj in statTypeList" :key="hobj.code" :value="hobj.code" :label="hobj.name"></vxe-option>
            </vxe-select>
          </template>
        </vxe-column>
        <vxe-column field="seq" title="顺序" min-width="40" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row }">
            <vxe-input v-model="row.seq" type="text"></vxe-input>
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <el-dialog title="指标" :show-close="false" v-model="showModuleDialog" append-to-body width="1000px" :close-on-click-modal="false" destroy-on-close v-if="showModuleDialog">
      <div class="tableBody" style="height: 600px">
        <vxe-table ref="staModuleTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="staModuleList" :loading="lloading" :row-config="{ keyField: 'majorCode', isHover: true }" :column-config="{ resizable: true }" :checkbox-config="{
                  checkMethod: checCheckboxkMethod2,
                  visibleMethod: showCheckboxkMethod2,
                  checkRowKeys: defaultSelecteRowKeys
                }" resizable show-overflow keep-source>

          <vxe-column type="checkbox" width="30px"></vxe-column>
          <vxe-column field="majorCode" title="专业编码"></vxe-column>
          <vxe-column field="majorName" title="专业名称"></vxe-column>

        </vxe-table>

        <div class="dialog-footer flex right justify-end">
          <el-button type="primary" @click="saveBacthModule('staModuleTableRef')">确定</el-button>
          <el-button @click="closeModuleDialog('staModuleTableRef')">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, defineExpose } from 'vue';
import { IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { isEmpty } from 'lodash';

// 全局变量定义区 ==========
defineExpose({
  initPage
});
interface RowVO {
  id: string;
  majorCode: string;
  majorName: string;
  majorGroup: string;
  seq: number; //顺序号
  indexId: string;
  qidxId: string;
  statType: string;
}
let { proxy }: any = getCurrentInstance();
let showLoading = ref(false); //刷新+表格加载状态
let showModuleDialog = ref(false); //添加弹框展示状态
let lloading = ref(false); //弹框表格数据加载状态
const qiIndexMajorList = reactive([]);
let qiIndex: any = null;

let statTypeList: any = reactive([]);

// 方法定义区 =============
onMounted(() => {
  getDictItemsList(); //批量获取字典
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['qiStatType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const faultGrades = dictTreeTypeItems.data.find((item: any) => item.code === 'qiStatType');
  statTypeList.push(...faultGrades.detailDataList);
}

function initPage(row: any) {
  qiIndex = row;
  findqiIndexMajorList();
}

// 获取列表
function findqiIndexMajorList() {
  showLoading.value = true;
  qiIndexMajorList.length = 0; //放入数据前清空数据
  const url = '/api/qi/qiIndexMajor/getIndexMajorList/' + qiIndex.indexCode;
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      if (!IsEmpty(res.data)) {
        qiIndexMajorList.push(...res.data);
        qiIndexMajorRowClick({ row: qiIndexMajorList[0], rowIndex: 0 });
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      showLoading.value = false;
    });
}
// 点击表格当前行
function qiIndexMajorRowClick({ row, rowIndex }) {
  proxy.$refs.qiIndexMajorTableRef.setCurrentRow(row);
}

// 弹框取消按钮
function closeModuleDialog() {
  showModuleDialog.value = false;
}
// 获取左侧表格数据
const staModuleList = reactive([]);
function findQiMajorList() {
  lloading.value = true;
  staModuleList.length = 0; //放入数据前清空数据
  const url = '/api/qi/major/getQiMajorList';
  proxy.$http
    //注意此处的数据条数
    .get(url)
    .then((res: any) => {
      if (!IsEmpty(res.data)) {
        staModuleList.push(...res.data);
      }
      lloading.value = false;
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
      lloading.value = false;
    });
}

//新增
async function handleAdd(row?: RowVO | number) {
  const $table = proxy.$refs.qiIndexMajorTableRef as any;
  if ($table) {
    const record = {
      id: null,
      majorCode: '',
      majorName: '',
      majorGroup: '',
      statType: '',
      seq: '', //顺序号
      indexId: qiIndex.id,
      indexCode: qiIndex.indexCode,
      qidxId: null
    };
    const { row: newRow } = await $table.insertAt(record, row);
    await $table.setEditRow(newRow);
  }
}

// 添加按钮

function addModuleDialog() {
  findQiMajorList();
  showModuleDialog.value = true;
}
function saveBacthModule() {
  const selectRows = (proxy.$refs.staModuleTableRef as any).getCheckboxRecords();
  if (selectRows.length > 0) {
    const addModelModuleList = [];
    for (const sltRow of selectRows) {
      const modelModule = qiIndexMajorList.find((qc: any) => qc.majorCode == sltRow.majorCode);
      if (isEmpty(modelModule)) {
        const addModelModule = {
          majorCode: sltRow.majorCode,
          majorName: sltRow.majorName,
          indexId: qiIndex.id,
          indexCode: qiIndex.indexCode,
          seq: sltRow.seq
        };
        addModelModuleList.push(addModelModule);
      }
    }
    if (addModelModuleList.length > 0) {
      const url = '/api/qi/qiIndexMajor/addQiIndexMajorList';
      proxy.$http
        .post(url, addModelModuleList)
        .then((res: any) => {
          findqiIndexMajorList(); // 获取检验仪器表格数据
          VxeMessage(res.status.msg, VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    } else {
      VxeMessage('请选择要添加的数据', VxeNotifyType.error);
    }
  }
  closeModuleDialog();
}

//批量保存
function saveList() {
  const $table = proxy.$refs.qiIndexMajorTableRef as any;
  const arrNews = $table.getInsertRecords();
  const arrModifies = $table.getUpdateRecords();
  arrNews.forEach((item: any, idx) => {
    const url = '/api/qi/qiIndexMajor/addQiIndexMajor';
    const data = item;
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
          findqiIndexMajorList();
        }
      })
      .catch((err) => {
        if (arrModifies.length <= 0 && idx === arrNews.length - 1) {
          VxeMessage('保存失败', VxeNotifyType.error);
        }
      });
  });
  arrModifies.forEach((item, idx) => {
    const url = '/api/qi/qiIndexMajor/updateQiIndexMajor';
    const data = item;
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (idx === arrModifies.length - 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
          findqiIndexMajorList();
        }
      })
      .catch((err) => {
        if (idx === arrModifies.length - 1) {
          VxeMessage('保存失败', VxeNotifyType.error);
        }
      });
  });
}
//删除
function handleDelete() {
  const $xTable = proxy.$refs.qiIndexMajorTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        selectRows.forEach((item, idx) => {
          const url = '/api/qi/qiIndexMajor/deleteQiIndexMajor';
          proxy.$http
            .post(url, item)
            .then((res: any) => {
              if (idx === selectRows.length - 1) {
                VxeMessage('删除成功', VxeNotifyType.success);
                findqiIndexMajorList();
              }
            })
            .catch((err) => {
              VxeMessage('删除时出现异常', VxeNotifyType.error);
            });
        });
      }
    });
}

function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}

let defaultSelecteRowKeys = reactive([]);
// 弹框 表格复选框(是否允许用户手动勾选)
function checCheckboxkMethod2({ row }: any) {
  defaultSelecteRowKeys.length = 0;
  const obj = qiIndexMajorList.filter((p: any) => {
    defaultSelecteRowKeys.push(p.majorCode);
    return p.majorCode == row.majorCode;
  });
  return obj.length == 0;
}

// 弹框 表格复选框 设置(是否显示复选框)
function showCheckboxkMethod2({ row }: any) {
  const obj = qiIndexMajorList.filter((p: any) => {});
  return obj.length == 0;
}
</script>

<style lang="scss" scoped>
#qiIndexMajor {
  height: 100%;
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
  .qiIndexMajorTable {
    height: calc(100% - 40px);
  }
}
</style>
